// -*-mode:c++; coding:utf-8-*-

#include <iostream>
#include <string>

using namespace std;

#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>

#include "protocol.hpp"
#include "io_service_pool_impl.hpp"
#include "session_manager.hpp"
#include "root_meta_cache.hpp"

using namespace xbase;

typedef boost::system::error_code error_code;

void on_got_root_meta(root_meta_cache *rmc_ptr, const error_code &ec)
{
	if(ec)
	{
		std::cout << "get root meta failed : " << ec
			<< " - " << ec.message() << std::endl;
	}
	else
	{
		std::cout << "root meta address is "
			<< rmc_ptr->get_root_tablet_info().to_string()
			<< std::endl;

		std::cout << "root meta tablet info is "
			<< rmc_ptr->get_root_server_address().to_string()
			<< std::endl;
	}
}

int main(int argc, char **argv)
{
	if(argc != 3)
	{
		cout <<argv[0]<<" master_ip master_port"<< endl;
		return 0;
	}

	boost::asio::ip::tcp::endpoint endpoint(
		boost::asio::ip::address::from_string(argv[1]),
		::atoi(argv[2])
		);

	boost::shared_ptr<io_service_pool> pool(new impl::single_io_service());
	client_options options;
	pool->set_options(options);
	pool->run();

	session_manager sm(*pool);
	root_meta_cache rmc(*pool, endpoint, sm);
	
	rmc.async_get_root_meta(boost::bind(on_got_root_meta, &rmc, _1));
	
	std::string input;
	while(std::cin >> input)
	{
		if(input == "close")
		{
			sm.close();
		}
		else if(input == "quit")
		{
			break;
		}
	}

	pool->stop();
	pool->join();

	return 0;
}
